package com.hw.dao.utils;


import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class OraclePageDaoBase1 {
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Resource(name = "remoteJdbcTemplate")
	private JdbcTemplate remoteJdbcTemplate;
	
	
	public JdbcTemplate getRemoteJdbcTemplate() {
		return remoteJdbcTemplate;
	}

	public void setRemoteJdbcTemplate(JdbcTemplate remoteJdbcTemplate) {
		this.remoteJdbcTemplate = remoteJdbcTemplate;
	}

	/**
	 * 分页查询记录
	 * @param sql
	 * @param pages
	 * @param rowMapper
	 * @param args
	 * @return
	 */
	public <X> Page<X> queryForPage(String sql,Page<X> pages,RowMapper<X> rowMapper,Object...args){
		int minNum = pages.getFirst();
		int maxNum = minNum + pages.getPageSize();
		StringBuffer pageSQL = new StringBuffer("SELECT * FROM (SELECT pagesql_TTT.*, ROWNUM RN FROM ("+sql+") pagesql_TTT WHERE ROWNUM < "+maxNum+") WHERE RN >= "+minNum);
		log.info("SQL:"+pageSQL.toString());
		for (Object object : args) {
			log.info("参数:"+object);
		}
		List<X> resultList = remoteJdbcTemplate.query(pageSQL.toString(), args, rowMapper);
		pages.setRows(resultList);
		if(pages.getTotal() ==-1){
			pages.setTotal(this.findCountTotal(sql, args));
		}
		
		return pages;
	}
	
	/**
	 * 查询记录总数
	 * @param sql
	 * @param args
	 * @return
	 */
	private int findCountTotal(String sql,Object...args){
		//判断当前是否有总记录数，如果没有，则查询一次总记录数
		String selectCountSQL = "select count(1) from ("+sql+") ";
		return remoteJdbcTemplate.queryForInt(selectCountSQL, args);
	}
	
}
